package com.wetao.education.module_reader.activity;

import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.wetao.education.module_reader.R;
import com.wetao.education.module_reader.contract.ReadPushCon;
import com.wetao.education.module_reader.presenter.ReadPushPre;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.adapter.RecycleHolder;
import com.wetao.lib_common.adapter.RecyclerAdapter;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.bean.response.ReadPushListInfo;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.view.OnMultiClickListener;

import java.util.ArrayList;
import java.util.List;


/**
 * 阅读推送记录页面
 */
@Route(path = ConstantArouter.PATH_READER_READPUSHACTIVITY)
public class ReadPushActivity extends BaseActivity<ReadPushCon.View, ReadPushPre> implements ReadPushCon.View, View.OnClickListener {


    private TextView tv_noData;
    private RelativeLayout rl_noData;
    private SmartRefreshLayout srl_refresh;

    private LRecyclerView lrv;
    private LRecyclerViewAdapter lrvAdapter;
    private RecyclerAdapter<ReadPushListInfo.Data.RecordsBean> adapter;
    private List<ReadPushListInfo.Data.RecordsBean> recordsBeans = new ArrayList<>();



    int current = 1;
    int pages = 1;
    int size = 10;
    int total = 1;

    @Override
    public int getLayoutId() {
        return R.layout.reader_push_main;
    }

    @Override
    public ReadPushPre createPresenter() {
        return new ReadPushPre(this);
    }

    @Override
    public ReadPushCon.View createView() {
        return this;
    }

    @Override
    public void init() {

        initTitleLayout();
        setTvTitle(getString(R.string.home_reader_push),true);
        rl_noData = findViewById(R.id.rl_noData);
        srl_refresh = findViewById(R.id.srl_refresh);
        tv_noData = findViewById(R.id.tv_noData);
        lrv = findViewById(R.id.lrv_read_push);

        iv_back.setOnClickListener(this);



        initRecycle();
        initSmartRefresh();
        getReadPushExamList(current);
    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }


    /**
     * 初始化刷新控件
     */
    private void initSmartRefresh() {

        srl_refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(final RefreshLayout refreshLayout) {
                LogUtils.i("---加载更多");
                if(pages>current){
                    getReadPushExamList(current + 1);
                }else {
                    refreshLayout.getLayout().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                        }
                    }, 1000);

                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                LogUtils.i("---下拉刷新");
                getReadPushExamList(current);
            }
        });
        srl_refresh.setRefreshHeader(new ClassicsHeader(this));
        srl_refresh.setRefreshFooter(new ClassicsFooter(this));
    }




    private void initRecycle() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        lrv.setLayoutManager(linearLayoutManager);
        lrv.setNestedScrollingEnabled(true);
        lrv.setOverScrollMode(View.OVER_SCROLL_NEVER);
        adapter = new RecyclerAdapter<ReadPushListInfo.Data.RecordsBean>(this, recordsBeans, R.layout.reader_push_main_item) {

            @Override
            public void convert(RecycleHolder holder, final ReadPushListInfo.Data.RecordsBean data, final int position) {
                holder.setText(R.id.tv_reader_name,data.getReadPushTitle());
                holder.setText(R.id.tv_read_push_time,"推送时间: " + data.getPushTime());
                TextView tv_classify = holder.findView(R.id.tv_read_classify);
                TextView tv_detail = holder.findView(R.id.tv_read_push_detail);
                tv_classify.setText(data.getSubjectName() + "阅读");
                if (data.getReadStatus() == 2){ //已阅读
                    tv_detail.setText("");
                    tv_detail.setSelected(true);
                    tv_classify.setBackground(getResources().getDrawable(R.drawable.common_text_read));
                    tv_classify.setTextColor(getResources().getColor(R.color.split));
                }else if (data.getReadStatus() == 3){
                    tv_classify.setTextColor(getResources().getColor(R.color.class_content));
                    tv_classify.setBackground(getResources().getDrawable(R.drawable.common_text_unread));
                    tv_detail.setText("阅读");
                    tv_detail.setSelected(false);
                }

                holder.itemView.setOnClickListener(new OnMultiClickListener() {
                    @Override
                    public void onMultiClick(View v) {
                        gotoDetailActivity(data);
                    }
                });

            }

        };
        lrvAdapter = new LRecyclerViewAdapter(adapter);
        lrv.setPullRefreshEnabled(false);
        lrv.setEmptyView(rl_noData);
        lrv.setAdapter(lrvAdapter);
    }

    /**
     * 查询试题
     * @param cur
     */
    private void getReadPushExamList(int cur) {
        getPresenter().getReadPushList(ComUtil.getHashmapByStr(
                new String[]{"pageNo","pageSize"},
                new String[]{ String.valueOf(cur), String.valueOf(size)})
                , false, false, cur);
    }


    public void resetNoMoreData(){
        if(srl_refresh!=null){
            srl_refresh.resetNoMoreData();//去除没有更多数据状态
        }
    }

    public void finishSmart(int cur) {
        if(cur == 1) {
            resetNoMoreData();
            recordsBeans.clear();
        }
        if(srl_refresh!=null){
            srl_refresh.getLayout().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(srl_refresh != null) {
                        srl_refresh.finishRefresh();
                        srl_refresh.finishLoadMore();
                    }
                }
            }, 500);
        }
    }

    private void refreshNoDataView() {
        if(recordsBeans != null && recordsBeans.size() > 0) {
            rl_noData.setVisibility(View.GONE);
            srl_refresh.setVisibility(View.VISIBLE);
        } else {
            rl_noData.setVisibility(View.VISIBLE);
            srl_refresh.setVisibility(View.GONE);
            tv_noData.setText("没有数据");
        }
    }


    @Override
    public void getReadPushListResult(ReadPushListInfo response, int cur) {
        finishSmart(cur);
        ReadPushListInfo.Data data = response.getData();
        if(data != null) {
            //current = markingListResp.getCurrent();  //获得的结果一直是1，不准
            current = cur;
            pages = data.getPages();
            size = data.getSize();
            total = data.getTotal();
            recordsBeans.addAll(data.getRecords());
            LogUtils.i("");
            lrv.setEmptyView(rl_noData);
            lrvAdapter.notifyDataSetChanged();
            refreshNoDataView();
        }

    }


    @Override
    public void getReadPushListFailed(int cur) {
        finishSmart(cur);
    }



    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back){
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getReadPushExamList(current = 1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private void gotoDetailActivity(ReadPushListInfo.Data.RecordsBean bean){
        if (bean.getFileUrl() == null){
            ToastUtil.initToast("没有找到文件路径");
            return;
        }
        ARouter.getInstance().build(ConstantArouter.PATH_READER_READPUSHDETAILACTIVITY)
                .withString("title",bean.getReadPushTitle())
                .withString("readPushItem",JsonUtils.toJson(bean))
                .withInt("state",bean.getReadStatus())
                .withString("records", JsonUtils.toJson(recordsBeans))
                .navigation();
    }


}
